package cn.stylefeng.guns.modular.gridsystem.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.core.context.constant.ConstantContextHolder;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.modular.gridsystem.activemq.ActiveMqProduceService;
import cn.stylefeng.guns.modular.gridsystem.annotion.custom.AppKey;
import cn.stylefeng.guns.modular.gridsystem.cache.MyStringCache;
import cn.stylefeng.guns.modular.gridsystem.constants.BizGatewayConstant;
import cn.stylefeng.guns.modular.gridsystem.constants.GatewayGrantStatusConstant;
import cn.stylefeng.guns.modular.gridsystem.entity.*;
import cn.stylefeng.guns.modular.gridsystem.enums.GatewayExceptionEnum;
import cn.stylefeng.guns.modular.gridsystem.event.ChannelInfoEvent;
import cn.stylefeng.guns.modular.gridsystem.event.CollectingDeviceInfoEvent;
import cn.stylefeng.guns.modular.gridsystem.event.FaultLogEvent;
import cn.stylefeng.guns.modular.gridsystem.event.param.CollectingDeviceInfo;
import cn.stylefeng.guns.modular.gridsystem.event.param.FaultLog;
import cn.stylefeng.guns.modular.gridsystem.event.param.SensorInfo;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizGatewayConfigMapper;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizGatewayConfigTemplateMapper;
import cn.stylefeng.guns.modular.gridsystem.model.param.*;
import cn.stylefeng.guns.modular.gridsystem.model.result.*;
import cn.stylefeng.guns.modular.gridsystem.mqtt.MqttProperties;
import cn.stylefeng.guns.modular.gridsystem.mqtt.MqttTopicConstant;
import cn.stylefeng.guns.modular.gridsystem.mqtt.MyMqttClient;
import cn.stylefeng.guns.modular.gridsystem.mqtt.result.FaultWarning;
import cn.stylefeng.guns.modular.gridsystem.service.*;
import cn.stylefeng.guns.modular.gridsystem.utils.MyConst;
import cn.stylefeng.guns.modular.gridsystem.utils.MyFileUtils;
import cn.stylefeng.guns.sys.modular.file.param.SysFileInfoParam;
import cn.stylefeng.guns.sys.modular.file.result.SysFileInfoResult;
import cn.stylefeng.guns.sys.modular.file.service.SysFileInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/v2/api")
@Slf4j
@RequiredArgsConstructor
public class ApiController {

    private final BizGatewayConfigMapper gatewayConfigMapper;

    private final BizGatewayConfigTemplateMapper configTemplateMapper;

    private final BizThreholdItemService bizThreholdItemService;

    private final BizGatewayService bizGatewayService;

    private final BizGatewayScheduleService bizGatewayScheduleService;

    private final BizUploadScoreService bizUploadScoreService;

    private final BizGatewayChannelService bizGatewayChannelService;

    private final BizExceptionService bizExceptionService;

    private final BizExceptionLogService exceptionLogService;

    private final SysFileInfoService sysFileInfoService;

    private final BizUploadQueueLogService uploadQueueLogService;

    private final ActiveMqProduceService activeMqProduce;

    private final BizIndustryInvolvedService industryInvolvedService;

    private final ThirdPartyInterconnectionService thirdPartyInterconnectionService;

    private final BizFaultModelService faultModelService;

    private final BizStationService stationService;

    private final BizDeviceService deviceService;

    private final PipConfigService pipConfigService;

    private final BizGatewayChannelService channelService;

    private final WpUploadLogService wpUploadLogService;

    private final BizCollectorConfigService bizCollectorConfigService;

    private final BizCollectionSampleManageService bizCollectionSampleManageService;

    private final BizGatewayTemperatureService bizGatewayTemperatureService;

    private final BizSoundCardLogService bizSoundCardLogService;

    private final MyStringCache myStringCache;

    private final GatewayTaskService gatewayTaskService;

    private final CollectionModelService modelService;

    private final BizGatewayNewFileService bizGatewayNewFileService;

    private final GatewayFirmwareService gatewayFirmwareService;

    private final ApplicationEventPublisher applicationEventPublisher;

    private final MyMqttClient myMqttClient;
    private final MqttProperties mqttProperties;

    @Value("${third-push-event.enable}")
    private Boolean pushEventEnable;


    /**
     * 采集端同步阈值
     * @param deviceCode
     * @return
     */
    @PostMapping("/getThreshold")
    public List<BizThreholdItem> syncThreshold(String deviceCode) {
        final BizGateway bizGateway = bizGatewayService.listByDeviceCode(deviceCode);
        if (ObjectUtil.isNull(bizGateway)) {
            return new ArrayList<>();
        }
        log.info("采集端同步阈值成功，设备编号为:{}",deviceCode);
        return bizThreholdItemService.listByGatewayId(bizGateway.getId());
    }

    /**
     * 同步采集时间
     * @param deviceCode
     * @return
     */
    @GetMapping("/synTime")
    public BizGatewaySchedule synTime(String deviceCode) {
        BizGateway bizGateway = bizGatewayService.listByDeviceCode(deviceCode);
        if (ObjectUtil.isEmpty(bizGateway)) {
            return null;
        }
        log.info("同步采集时间成功，设备编号为:{}",deviceCode);
        return bizGatewayScheduleService.oneByGatewayId(bizGateway.getId());
    }

    /**
     * 采集设备上传状态
     * @param deviceCode
     * @param ip
     */
    @GetMapping("/heartBeat")
    public void heartBeat(String deviceCode, String ip) {
        final BizGatewayParam bizGatewayParam = new BizGatewayParam();
        bizGatewayParam.setGatewayCode(deviceCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(bizGatewayParam);
        if (ObjectUtil.isNotNull(bizGateway)) {
            bizGateway.setGatewayIp(ip);
            bizGatewayService.updateById(bizGateway);

            //第三方采集设备信息事件
            if (pushEventEnable) {
                final CollectingDeviceInfo collectingDeviceInfo = new CollectingDeviceInfo();
                collectingDeviceInfo.setGatewayCode(deviceCode);
                collectingDeviceInfo.setCreateTime(DateUtil.today());
                collectingDeviceInfo.setDataReportingSwitch(bizGateway.getDataReportingSwitch());
                collectingDeviceInfo.setDeviceIp(bizGateway.getGatewayIp());
                collectingDeviceInfo.setStatus(bizGateway.getOnlineStatus());
                applicationEventPublisher.publishEvent(new CollectingDeviceInfoEvent(collectingDeviceInfo));
            }
        }
        bizGatewayService.editByGatewayCode(deviceCode);
        log.info("采集设备上传状态成功，设备编号为：{},ip为：{}",deviceCode,ip);
    }

    /**
     * 采集设备上报故障文件和记录(采集端只做1:1)
     * @param file
     * @param verfyTime
     * @param gatewayCode
     * @param micRouter
     * @param score
     * @param accessToken
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadFaultLog")
    public ResponseData uploadFaultLog(@RequestPart(value = "file") MultipartFile file, @RequestParam("verfyTime") String verfyTime, @RequestParam("gatewayCode") String gatewayCode, @RequestParam("micRouter") String micRouter, @RequestParam("score") String score, @RequestParam("accessToken") String accessToken) throws Exception {
        //查询网关
        final BizGateway bizGateway = bizGatewayService.listByDeviceCode(gatewayCode);
        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }
        //接收文件
        final Long aLong = sysFileInfoService.uploadFile(file);
        final SysFileInfoResult fileInfoResult = sysFileInfoService.getFileInfoResult(aLong);

        //查询通道的Query
        final LambdaQueryWrapper<BizGatewayChannel> queryWrapper = new LambdaQueryWrapper<>();
        Integer gatewayId = bizGateway.getId();
        queryWrapper.eq(BizGatewayChannel::getGatewayId, gatewayId);
        queryWrapper.eq(BizGatewayChannel::getChannel, micRouter);
        final BizGatewayChannel one = channelService.getOne(queryWrapper);
        if (ObjectUtil.isNull(one)) {
            throw new ServiceException(MyConst.CHANNEL_NOT_EXIST);
        }

        //查询设备，找到它的所属行业
        final Integer deviceId = one.getDeviceId();
        final BizDevice device = deviceService.getById(deviceId);
        if (ObjectUtil.isNull(device)) {
            throw new ServiceException(MyConst.DEVICE_NOT_EXIST);
        }
        final Integer industryId = device.getIndustryId();
        final BizIndustryInvolved industryInvolved = industryInvolvedService.getById(industryId);
        if (ObjectUtil.isNull(industryInvolved)) {
            throw new ServiceException(MyConst.INDUSTRY_NOT_EXIST);
        }
        //查询到模型的分组号
        final Integer groupId = industryInvolved.getGroupId();

        //将待验证数据推入队列
        final BizUploadQueueLogParam bizUploadQueueLogParam = new BizUploadQueueLogParam();
        bizUploadQueueLogParam.setGatewayId(bizGateway.getId());
        bizUploadQueueLogParam.setGatewayChannel(micRouter);
        bizUploadQueueLogParam.setFilePath(fileInfoResult.getFileBucket() + "/" + fileInfoResult.getFileObjectName());
        bizUploadQueueLogParam.setScore(score);
        bizUploadQueueLogParam.setGroupId(String.valueOf(groupId));
        bizUploadQueueLogParam.setCreatedAt(DateUtil.parse(verfyTime));
        bizUploadQueueLogParam.setGatewayCode(gatewayCode);
        bizUploadQueueLogParam.setStatus(0);
        bizUploadQueueLogParam.setAccessToken(accessToken);
        uploadQueueLogService.addAndReturnId(bizUploadQueueLogParam);
        //添加到队列进行1：N
        activeMqProduce.sendT(bizUploadQueueLogParam);
        return ResponseData.success();
    }

    /**
     * 获取采集端分数(采集端1:1和1：N)
     * @param file
     * @param gatewayCode
     * @param faultText
     * @param micRouter
     * @param score
     * @param accessToken
     * @param verfyTime
     * @return
     */
    @PostMapping("/getScore")
    public ResponseData getScore(@RequestPart(value = "file") MultipartFile file, @RequestParam("gatewayCode") String gatewayCode, @RequestParam("faultText") String faultText, @RequestParam("micRouter") String micRouter, @RequestParam("score") String score, @RequestParam("accessToken") String accessToken, @RequestParam("verfyTime") String verfyTime) {

        //接收文件
        //final Long aLong = sysFileInfoService.uploadFile(file);
        final Long aLong = sysFileInfoService.uploadFile(file,"error");
        final SysFileInfoResult fileInfoResult = sysFileInfoService.getFileInfoResult(aLong);
        final BizGateway bizGateway = bizGatewayService.listByDeviceCode(gatewayCode);
        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }

        //电站Id
        final Integer stationId = bizGateway.getStationId();

        //查询电站
        final BizStation station = stationService.getById(stationId);
        if (ObjectUtil.isNull(station)) {
            throw new ServiceException(MyConst.STATION_NOT_EXIST);
        }

        //查询通道的Query
        final LambdaQueryWrapper<BizGatewayChannel> queryWrapper = new LambdaQueryWrapper<>();
        Integer gatewayId = bizGateway.getId();
        queryWrapper.eq(BizGatewayChannel::getGatewayId, gatewayId);
        queryWrapper.eq(BizGatewayChannel::getChannel, micRouter);
        final BizGatewayChannel bizGatewayChannel = channelService.getOne(queryWrapper);
        if (ObjectUtil.isNull(bizGatewayChannel)) {
            throw new ServiceException(MyConst.CHANNEL_NOT_EXIST);
        }

        final BizExceptionParam bizExceptionParam = new BizExceptionParam();
        bizExceptionParam.setDeviceId(bizGatewayChannel.getDeviceId());
        bizExceptionParam.setErrorName(faultText);
        bizExceptionParam.setGatewayCode(gatewayCode);
        bizExceptionParam.setAccessToken(accessToken);
        bizExceptionParam.setCreatedAt(verfyTime);
        final BizException bizException = bizExceptionService.oneByErrorNameAndToday(bizExceptionParam);

        //查询设备
        final Integer deviceId = bizGatewayChannel.getDeviceId();
        final BizDevice device = deviceService.getById(deviceId);
        if (ObjectUtil.isNull(device)) {
            throw new ServiceException(MyConst.DEVICE_NOT_EXIST);
        }

        //第一次故障时间
        String firstTime;
        Integer bizExceptionId;
        int errorType = 0;
        if (!MyConst.UNKNOWN_FAULT.equals(faultText)) {
            errorType = 1;
        }
        if (ObjectUtil.isNotNull(bizException) && faultText.equals(bizException.getErrorName()) && gatewayCode.equals(bizException.getGatewayCode()) && bizGatewayChannel.getDeviceId().equals(bizException.getDeviceId())) {
            // 当天有数据
            firstTime = DateUtil.formatDateTime(bizException.getCreatedAt());
            bizExceptionId = bizException.getId();
        } else {
            // 当天无数据
            firstTime = verfyTime;
            final BizExceptionParam bizExceptionInsertParam = new BizExceptionParam();
            bizExceptionInsertParam.setDeviceId(bizGatewayChannel.getDeviceId());
            bizExceptionInsertParam.setErrorName(faultText);
            bizExceptionInsertParam.setCreatedAt(firstTime);
            bizExceptionInsertParam.setErrorType(errorType);
            bizExceptionInsertParam.setGatewayCode(gatewayCode);
            bizExceptionInsertParam.setStatus(0);
            bizExceptionInsertParam.setAccessToken(accessToken);
            bizExceptionId = bizExceptionService.addAndReturnId(bizExceptionInsertParam);
            if (bizExceptionId == 0) {
                throw new ServiceException(MyConst.INSERT_EXCEPTION_ERROR);
            }
        }
        final BizExceptionLogParam bizExceptionLogparam = new BizExceptionLogParam();
        bizExceptionLogparam.setExceptionId(bizExceptionId);
        bizExceptionLogparam.setCreatedAt(firstTime);
        String filePath = fileInfoResult.getFileBucket() + "/" + fileInfoResult.getFileObjectName();
        if (ObjectUtil.isNotNull(fileInfoResult)) {
            bizExceptionLogparam.setFileName(filePath);
        }
        bizExceptionLogparam.setGatewayChannel(micRouter);
        bizExceptionLogparam.setGatewayCode(gatewayCode);
        bizExceptionLogparam.setAccessToken(accessToken);
        bizExceptionLogparam.setVoiceScore(score);
        //设置为1:1时间
        bizExceptionLogparam.setExceptionTime(DateUtil.parse(verfyTime));
        bizExceptionLogparam.setCreateTime(DateUtil.parse(verfyTime));
        final boolean exceptionLog = exceptionLogService.add(bizExceptionLogparam);
        if (!exceptionLog) {
            throw new ServiceException(MyConst.INSERT_EXCEPTION_LOG_ERROR);
        }

        //第三方事件
        if (pushEventEnable) {
            FaultLog faultLog = new FaultLog();
            faultLog.setGatewayCode(gatewayCode);
            faultLog.setChannel(micRouter);
            faultLog.setFaultCategory(faultText);
            faultLog.setFaultType(bizExceptionParam.getErrorType());
            faultLog.setAccessToken(accessToken);
            faultLog.setFaultType(errorType);
            faultLog.setFaultTime(DateUtil.formatDateTime(bizExceptionLogparam.getExceptionTime()));
            faultLog.setStatus(bizExceptionParam.getStatus());
            faultLog.setFilePath(MyFileUtils.getUploadPath() + "/" + filePath);
            if (errorType == 1) {
                BizFaultModel faultModel = faultModelService.getOneByAccessToken(accessToken);
                if (ObjectUtil.isNotNull(faultModel)) {
                    String[] modelFile = faultModel.getModelFile().split(",");
                    if (modelFile.length > 0) {
                        String path = MyFileUtils.getUploadPath() + "/" + modelFile[0];
                        if (FileUtil.exist(path)) {
                            faultLog.setModelFilePath(path);
                        }
                    }
                }
            }
            applicationEventPublisher.publishEvent(new FaultLogEvent(faultLog));
        }

        //mqtt推送
        if (mqttProperties.isEnable()) {
            FaultWarning faultWarning = new FaultWarning();
            faultWarning.setStationName(station.getStationName());
            faultWarning.setWarnName(faultText);
            faultWarning.setStationAddress(station.getStationAddress());
            faultWarning.setGatewayCode(gatewayCode);
            faultWarning.setGatewayChannel(bizGatewayChannel.getChannel());
            faultWarning.setDeviceId(device.getId());
            faultWarning.setDeviceName(device.getDeviceName());
            faultWarning.setInstallLocation(bizGatewayChannel.getInstallLocation());
            faultWarning.setVoiceUrl(filePath);
            faultWarning.setDateTime(verfyTime);
            faultWarning.setScore(score);
            faultWarning.setErrorType(errorType);
            if (errorType == 0) {
                faultWarning.setAccessToken("0");
            } else {
                faultWarning.setAccessToken(accessToken);
            }
            myMqttClient.publish(MqttTopicConstant.ALARM_PUSH, JSONUtil.toJsonStr(faultWarning));
        }

        //获取第三方列表
        final ThirdPartyInterconnectionParam interconnectionParam = new ThirdPartyInterconnectionParam();
        final ThirdIntegerfaceParam interfaceParam = new ThirdIntegerfaceParam();

        if (ObjectUtil.isNotNull(station)) {
            Long orgId = station.getOrgId();
            interconnectionParam.setOrgId(orgId);
            interfaceParam.setStationName(station.getStationName());
            interfaceParam.setStationAddress(station.getStationAddress());
        }

        interfaceParam.setGatewayCode(bizExceptionLogparam.getGatewayCode());
        interfaceParam.setGatewayChannel(bizExceptionLogparam.getGatewayChannel());
        interfaceParam.setWarnName(faultText);
        interfaceParam.setVoiceUrl(bizExceptionLogparam.getFileName());
        interfaceParam.setDateTime(bizExceptionLogparam.getCreateTime().toString());
        interfaceParam.setScore(score);

        final List<ThirdPartyInterconnection> list = thirdPartyInterconnectionService.list(interconnectionParam);
        interfaceParam.setList(list);
        interfaceParam.setDeviceName(device.getDeviceName());

        if (list.size() > 0) {
            activeMqProduce.sendThirdParty(interfaceParam);
            log.info("不经过引擎加入到第三方推送队列");
        }

        return ResponseData.success();
    }

    /**
     * 上报分数
     * @param gatewayCode
     * @param micRouter
     * @param score
     * @param accessToken
     * @param status
     * @return
     * @throws Exception
     */
    @PostMapping("/addGateWayLog")
    public ResponseData addGateWayLog(@RequestParam("gatewayCode") String gatewayCode, @RequestParam("micRouter") String micRouter, @RequestParam("score") String score, @RequestParam("accessToken") String accessToken, @RequestParam("status") int status) throws Exception {

        final BizGateway bizGateway = bizGatewayService.listByDeviceCode(gatewayCode);
        final BizUploadScoreParam bizUploadScore = new BizUploadScoreParam();
        bizUploadScore.setGatewayChannel(micRouter);
        bizUploadScore.setScore(score);
        bizUploadScore.setCreatedAt(DateUtil.date());
        bizUploadScore.setAccessToken(accessToken);
        final LambdaQueryWrapper<BizGatewayChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(bizGateway)) {
            Integer gatewayId = bizGateway.getId();
            bizUploadScore.setGatewayId(gatewayId);
            queryWrapper.eq(BizGatewayChannel::getGatewayId, gatewayId);
            LambdaUpdateWrapper<BizGateway> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(BizGateway::getOnlineStatus, BizGatewayConstant.ONLINE_STATUS_ON);
            updateWrapper.eq(BizGateway::getId, gatewayId);
            bizGatewayService.update(updateWrapper);
        }
        queryWrapper.eq(BizGatewayChannel::getChannel, micRouter);
        final List<BizGatewayChannel> channelList = channelService.list(queryWrapper);
        if (!channelList.isEmpty()) {
            for (BizGatewayChannel item : channelList) {
                item.setStatus(status);
                channelService.updateById(item);
                bizUploadScore.setDeviceId(item.getDeviceId());
            }
        }

        if("0".equals(score)){
            return ResponseData.success("分数为0，未进行记录");
        }
        boolean bizUploadScoreAdd = bizUploadScoreService.add(bizUploadScore);
        //第三方传感器信息事件
        if (pushEventEnable) {
            SensorInfo sensorInfo = new SensorInfo();
            sensorInfo.setGatewayCode(gatewayCode);
            sensorInfo.setChannel(micRouter);
            sensorInfo.setStatus(status);
            sensorInfo.setInstallLocation(channelList.get(0).getInstallLocation());
            sensorInfo.setCreateTime(DateUtil.today());
            applicationEventPublisher.publishEvent(new ChannelInfoEvent(sensorInfo));
        }
        if (!bizUploadScoreAdd) {
            throw new ServiceException(MyConst.INSERT_UPLOAD_SCORE_ERROR);
        }
        return ResponseData.success("添加成功");
    }

    /**
     * 查询行业列表
     * @return
     */
    @GetMapping("/getIndustryInvolved")
    @AppKey
    public ResponseData getIndustryInvolved() {
        final List<BizIndustryInvolved> list = industryInvolvedService.list();
        return ResponseData.success(list);
    }

    /**
     * 查询故障模型
     * @param industryInvolvedId
     * @param faultLevel
     * @return
     */
    @GetMapping("/getFaultModel")
    @AppKey
    public ResponseData getFaultModel(@RequestParam(name = "industryInvolvedId") Integer industryInvolvedId, @RequestParam(name = "faultLevel", required = false) String faultLevel) {
        final BizIndustryInvolved byId = industryInvolvedService.getById(industryInvolvedId);
        final Integer groupId = byId.getGroupId();
        final BizFaultModelParam modelParam = new BizFaultModelParam();
        if (ObjectUtil.isNotEmpty(groupId)) {
            modelParam.setGroupId(groupId);
        }
        if (ObjectUtil.isNotEmpty(faultLevel)) {
            modelParam.setFaultLevel(faultLevel);
        }
        final List<BizFaultModel> list = faultModelService.list(modelParam);
        return ResponseData.success(list);
    }

    /**
     * 查询故障模型
     * @param mId
     * @return
     */
    @PostMapping("/getFaultModelList")
    @AppKey
    public ResponseData getFaultModelList(@RequestParam(name = "mId", required = false) Integer mId) {
        final BizFaultModelParam param = new BizFaultModelParam();
        if (ObjectUtil.isNotEmpty(mId)) {
            param.setId(mId);
        }
        final List<BizFaultModel> list = faultModelService.list(param);
        return ResponseData.success(list);
    }

    /**
     * 查询电站列表
     * @param appKey
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping("/getStationList")
    public ResponseData getStationList(@RequestHeader String appKey,
                                       @RequestParam(name = "pageNo") int pageNo,
                                       @RequestParam(name = "pageSize") int pageSize) {
        final ThirdPartyInterconnection thirdPartyInterconnection = thirdPartyInterconnectionService.getByAppKey(appKey);
        if (ObjectUtil.isNull(thirdPartyInterconnection)) {
            throw new ServiceException("appKey错误");
        }
        final Long orgId = thirdPartyInterconnection.getOrgId();
        final BizStationParam stationParam = new BizStationParam();
        stationParam.setOrgId(orgId);
        final PageResult<BizStationResult> bizStationPageResult = stationService.pageList(stationParam);
        return ResponseData.success(bizStationPageResult);
    }

    /**
     * 查询电站信息
     * @param stationId
     * @return
     */
    @PostMapping("/getStationInfo")
    @AppKey
    public ResponseData getStationInfo(@RequestParam(name = "stationId") Integer stationId) {
        final BizStation station = stationService.getById(stationId);
        if (ObjectUtil.isEmpty(station)) {
            throw new ServiceException(MyConst.STATION_NOT_EXIST);
        }
        return ResponseData.success(station);
    }

    /**
     * 查询设备列表
     * @param stationId
     * @param industryInvolvedId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping("/getDeviceList")
    @AppKey
    public ResponseData getDeviceList(@RequestParam(name = "stationId") int stationId,
                                      @RequestParam(name = "industryInvolvedId") Integer industryInvolvedId,
                                      @RequestParam(name = "pageNo") int pageNo,
                                      @RequestParam(name = "pageSize") int pageSize) {
        final BizDeviceParam deviceParam = new BizDeviceParam();
        deviceParam.setStationId(stationId);
        if (ObjectUtil.isNotEmpty(industryInvolvedId)) {
            deviceParam.setIndustryId(industryInvolvedId);
        }
        final PageResult<BizDeviceResult> page = deviceService.page(deviceParam);
        return ResponseData.success(page);
    }

    /**
     * 查询所有设备列表
     * @param deviceId
     * @return
     */
    @PostMapping("/getAllDeviceList")
    @AppKey
    public ResponseData getAllDeviceList(@RequestParam(name = "deviceId", required = false) Integer deviceId) {
        final BizDeviceParam deviceParam = new BizDeviceParam();
        if (ObjectUtil.isNotEmpty(deviceId)) {
            deviceParam.setId(deviceId);
        }
        return ResponseData.success(deviceService.list(deviceParam));
    }

    /**
     * 查询网关列表
     * @param stationId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getGatewayList")
    @AppKey
    public ResponseData getGatewayList(@RequestParam(name = "stationId") int stationId,
                                       @RequestParam(name = "pageNo") int pageNo,
                                       @RequestParam(name = "pageSize") int pageSize) {
        final BizGatewayParam gatewayParam = new BizGatewayParam();
        gatewayParam.setStationId(stationId);
        final PageResult<BizGatewayResult> page = bizGatewayService.page(gatewayParam);
        return ResponseData.success(page);
    }

    /**
     * 查询设备对应的网关与网关通道
     * @param deviceId
     * @return
     */
    @PostMapping("/getGatewayChannel")
    @AppKey
    public ResponseData getGatewayChannel(@RequestParam(name = "deviceId") int deviceId) {
        final BizDevice device = deviceService.getById(deviceId);
        final Integer stationId = device.getStationId();
        final LambdaQueryWrapper<BizGateway> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizGateway::getStationId, stationId);
        final List<BizGatewayResult> list = bizGatewayService.getListAndChannel(queryWrapper);
        return ResponseData.success(list);
    }


    /**
     * 查询故障列表
     * @param deviceId
     * @param startTime
     * @param endTime
     * @param micRouter
     * @param gatewayCode
     * @param accessToken
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping("/getExceptionLog")
    @AppKey
    public ResponseData getExceptionLog(@RequestParam(name = "deviceId") int deviceId,
                                        @RequestParam(name = "startTime", required = false) String startTime,
                                        @RequestParam(name = "endTime", required = false) String endTime,
                                        @RequestParam(name = "micRouter", required = false) String micRouter,
                                        @RequestParam(name = "gatewayCode", required = false) String gatewayCode,
                                        @RequestParam(name = "accessToken", required = false) String accessToken,
                                        @RequestParam(name = "pageNo") int pageNo,
                                        @RequestParam(name = "pageSize") int pageSize) {
        final LambdaQueryWrapper<BizException> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizException::getDeviceId, deviceId);
        if (ObjectUtil.isNotEmpty(startTime)) {
            wrapper.ge(BizException::getCreatedAt, DateUtil.parse(startTime));
        }
        if (ObjectUtil.isNotEmpty(endTime)) {
            wrapper.le(BizException::getCreatedAt, DateUtil.parse(endTime));
        }
        if (ObjectUtil.isNotEmpty(gatewayCode)) {
            wrapper.eq(BizException::getGatewayCode, gatewayCode);
        }
        if (ObjectUtil.isNotEmpty(accessToken)) {
            wrapper.eq(BizException::getAccessToken, accessToken);
        }
        final List<BizException> bizExceptions = bizExceptionService.list(wrapper);
        final Set<Integer> set = new HashSet<>();
        bizExceptions.forEach(bizException -> set.add(bizException.getId()));
        final BizExceptionLogParam exceptionLogParam = new BizExceptionLogParam();
        if (ObjectUtil.isNotEmpty(micRouter)) {
            exceptionLogParam.setGatewayChannel(micRouter);
        }
        final PageResult<BizExceptionLogResult> page = exceptionLogService.thirdPageList(exceptionLogParam, set, deviceId);
        return ResponseData.success(page);
    }

    /**
     * 查询故障详情
     * @param eId
     * @return
     */
    @PostMapping("/getExceptionLogInfo")

    @AppKey
    public ResponseData getExceptionLogInfo(@RequestParam(name = "eId") Integer eId) {
        return ResponseData.success(exceptionLogService.getExceptionLog(eId));
    }

    /**
     * 管道配置
     * @return
     */
    @PostMapping("/getPipConfig")
    public ResponseData getPipConfig() {
        //每小时激活次数
        final String activateNumber = pipConfigService.detailByCode("FREQUENCY_OF_HOUR");
        //发射时长
        final String launchTime = pipConfigService.detailByCode("LAUNCH_TIME");
        //发声频率
        final String soundFrequency = pipConfigService.detailByCode("SOUND_FREQUENCY");
        final Map<String, String> map = MapUtil.newHashMap();
        map.put("activateNumber", activateNumber);
        map.put("launchTime", launchTime);
        map.put("soundFrequency", soundFrequency);
        return ResponseData.success(map);
    }

    /**
     * 倾角数据上传
     * @param dip
     * @param gatewayCode
     * @param micRouter
     * @return
     */
    @PostMapping("/addDipLog")
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addDipLog(@RequestParam(name = "dip") String dip, @RequestParam(name = "gatewayCode") String gatewayCode, @RequestParam(name = "micRouter") String micRouter) {
        final WpUploadLogParam wpUploadLogParam = new WpUploadLogParam();
        wpUploadLogParam.setDip(dip);
        final BizGatewayParam bizGatewayParam = new BizGatewayParam();
        bizGatewayParam.setGatewayCode(gatewayCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(bizGatewayParam);
        log.info("网关编号：{},dip：{},通道：{}", gatewayCode, dip, micRouter);

        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }

        final Integer gatewayId = bizGateway.getId();
        final BizGatewayChannel bizGatewayChannel = bizGatewayChannelService.listByGatewayId(gatewayId, micRouter);
        if (bizGatewayChannel != null) {
            wpUploadLogParam.setChannelId(bizGatewayChannel.getId());
            final BizThreholdItemParam bizThreholdItemParam = new BizThreholdItemParam();
            bizThreholdItemParam.setGatewayId(gatewayId);
            bizThreholdItemParam.setGatewayChannel(bizGatewayChannel.getChannel());
            final BizThreholdItem bizThreholdItem = bizThreholdItemService.threholdItemByChannelAndGatewayId(bizThreholdItemParam);
            if (bizThreholdItem != null) {
                final String thresholdValue = bizThreholdItem.getThresholdValue();
                final String[] thresholdValues = thresholdValue.split(",");
                final String[] dips = dip.split(",");
                if (dips.length == 3 && thresholdValues.length == 2) {
                    if (Double.parseDouble(dips[0]) > Math.abs(Double.parseDouble(thresholdValues[0])) || Double.parseDouble(dips[0]) < -Math.abs(Double.parseDouble(thresholdValues[0]))) {
                        addLog(MyConst.X_BEYOND_THRESHOLD, gatewayCode, gatewayId, micRouter, dips[0], bizGatewayChannel.getDeviceId());
                    }
                    if (Double.parseDouble(dips[1]) > Math.abs(Double.parseDouble(thresholdValues[1])) || Double.parseDouble(dips[1]) < -Math.abs(Double.parseDouble(thresholdValues[1]))) {
                        addLog(MyConst.Y_BEYOND_THRESHOLD, gatewayCode, gatewayId, micRouter, dips[1], bizGatewayChannel.getDeviceId());
                    }
                }
            }
        }
        //添加倾角日志
        wpUploadLogService.add(wpUploadLogParam);
        //修改通道状态为正常
        final LambdaQueryWrapper<BizGatewayChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(bizGateway)) {
            queryWrapper.eq(BizGatewayChannel::getGatewayId, gatewayId);
        }
        queryWrapper.eq(BizGatewayChannel::getChannel, micRouter);
        final BizGatewayChannel one = channelService.getOne(queryWrapper);
        if (ObjectUtil.isNotNull(one)) {
            one.setStatus(1);
            channelService.updateById(one);
        }

        return ResponseData.success();
    }

    /**
     * 获取倾角上传频率
     */
    @GetMapping("/getDipUploadFrequency")
    public String getDipUploadFrequency() {
        return ConstantContextHolder.getDipUploadFrequency();
    }

    /**
     * 获取主动发声采集器配置
     * @param deviceCode
     * @param ip
     * @return
     */
    @GetMapping("/getActiveVoiceConfig")
    public Map<String, Object> getActiveVoiceConfig(String deviceCode, String ip) {
        final BizGatewayParam bizGatewayParam = new BizGatewayParam();
        bizGatewayParam.setGatewayCode(deviceCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(bizGatewayParam);
        final HashMap<String, Object> map = MapUtil.newHashMap();
        if (ObjectUtil.isNotNull(bizGateway)) {
            final Integer gatewayId = bizGateway.getId();
            bizGateway.setGatewayIp(ip);
            bizGatewayService.updateById(bizGateway);
            final String frequency = bizCollectorConfigService.getByCode(gatewayId, "frequency");
            final String volumeActiveVoice = bizCollectorConfigService.getByCode(gatewayId, "volume_active_voice");
            final String workingHours = bizCollectorConfigService.getByCode(gatewayId, "working_hours");
            final String intermittentTime = bizCollectorConfigService.getByCode(gatewayId, "intermittent_time");
            map.put("frequency", frequency);
            map.put("volumeActiveVoice", volumeActiveVoice);
            map.put("workingHours", workingHours);
            map.put("intermittentTime", intermittentTime);
        }

        return map;
    }

    /**
     * 获取网关上传数据开关
     * @param deviceCode
     * @return
     */
    @GetMapping("/getGatewayUploadSwitch")
    public ResponseData getGatewayUploadSwitch(String deviceCode) {
        final BizGatewayParam bizGatewayParam = new BizGatewayParam();
        bizGatewayParam.setGatewayCode(deviceCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(bizGatewayParam);
        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }
        final Integer reportingSwitch = bizGateway.getDataReportingSwitch();
        return new SuccessResponseData(reportingSwitch);
    }

    @PostMapping("/warning")
    public ResponseData warning(@RequestBody ThirdResult thirdResult) {
        log.info("接收到报警：{}", thirdResult);
        return ResponseData.success();
    }

    /**
     * 获取网关CPU温度
     */
    @PostMapping("/addCollectTemp")
    public ResponseData addCollectTemp(String deviceCode, String temp) {
        myStringCache.put(deviceCode + "_collectTemp", temp);
        final BizGatewayParam gatewayParam = new BizGatewayParam();
        gatewayParam.setGatewayCode(deviceCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(gatewayParam);

        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }

        final BizGatewayTemperatureParam gatewayTemperatureParam = new BizGatewayTemperatureParam();
        gatewayTemperatureParam.setGatewayId(bizGateway.getId());
        gatewayTemperatureParam.setTemperature(temp);
        bizGatewayTemperatureService.add(gatewayTemperatureParam);
        bizGatewayService.editByGatewayCode(deviceCode);
        return ResponseData.success();
    }

    /**
     * 获取网关CPU温度
     */
    @PostMapping("/getCollectTemp")
    public ResponseData getCollectTemp(String deviceCode) {
        return ResponseData.success(myStringCache.get(deviceCode + "_collectTemp"));
    }

    /**
     * 上报采集端样本
     */
    @PostMapping("/addCollectionSample")
    public ResponseData addCollectionSample(@RequestPart MultipartFile file, BizCollectionSampleManageParam bizCollectionSampleManage) {
        final BizGatewayParam gatewayParam = new BizGatewayParam();
        gatewayParam.setGatewayCode(bizCollectionSampleManage.getGatewayCode());
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(gatewayParam);
        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }
       // final Long aLong = sysFileInfoService.uploadFile(file);
        final Long aLong = sysFileInfoService.uploadFile(file,"normal");
        bizCollectionSampleManage.setFileId(aLong);
        bizCollectionSampleManage.setGatewayId(bizGateway.getId());
        // 设置上报时间为服务器时间，是因为采集端上报的时间不准确，所以需要接口重新设置创建时间
        bizCollectionSampleManage.setCreateAt(DateTime.now().toString());
        bizCollectionSampleManageService.add(bizCollectionSampleManage);
        return ResponseData.success();
    }

    /**
     * 上报声卡状态
     */
    @GetMapping("/uploadSoundCardStatus")
    public ResponseData addCollectionSample(String deviceCode, String message) {
        final BizGatewayParam gatewayParam = new BizGatewayParam();
        gatewayParam.setGatewayCode(deviceCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(gatewayParam);
        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }
        final BizSoundCardLogParam soundCardLogParam = new BizSoundCardLogParam();
        soundCardLogParam.setGatewayId(bizGateway.getId());
        soundCardLogParam.setMessage(message);
        bizSoundCardLogService.add(soundCardLogParam);
        return ResponseData.success();
    }

    /**
     * 获取网关配置
     */
    @GetMapping("/getGatewayConfig")
    public ResponseData getGatewayConfig(String deviceCode) {
        BizGatewayParam gatewayParam = new BizGatewayParam();
        gatewayParam.setGatewayCode(deviceCode);
        final BizGateway gateway = bizGatewayService.gatewayByGatewayCode(gatewayParam);

        if (ObjectUtil.isEmpty(gateway)) {
            throw new ServiceException("this is new device");
        }

        List<BizGatewayConfig> configList = gatewayConfigMapper.selectList(new LambdaQueryWrapper<BizGatewayConfig>().eq(BizGatewayConfig::getGatewayId, gateway.getId()));

        Map<String, Object> cfgMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(configList)) {
            for (BizGatewayConfig cfg : configList) {
                BizGatewayConfigTemplate template = configTemplateMapper.selectById(cfg.getTemplateId());
                if (ObjectUtil.isEmpty(template)) {
                    continue;
                }
                if ("2".equals(template.getConfigType())) {
                    cfgMap.put(cfg.getGatewayConfigCode(), "true".equalsIgnoreCase(cfg.getConfigValue()));
                } else if ("3".equals(template.getConfigType())) {
                    cfgMap.put(cfg.getGatewayConfigCode(), Integer.parseInt(cfg.getConfigValue()));
                } else {
                    cfgMap.put(cfg.getGatewayConfigCode(), cfg.getConfigValue());
                }
            }
        }

        return ResponseData.success(cfgMap);
    }

    /**
     * 初始化网关设备
     *
     * @return
     */
    @GetMapping("/initGatewayDevice")
    public ResponseData initGatewayDevice(String deviceCode) {
        final BizGatewayParam gatewayParam = new BizGatewayParam();
        gatewayParam.setGatewayCode(deviceCode);
        log.info(">>> 上报网关的deviceCode为：{}", deviceCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(gatewayParam);
        if (ObjectUtil.isNull(bizGateway)) {
            // 设置上报时间
            gatewayParam.setCreatedAt(DateUtil.now());
            gatewayParam.setDataReportingSwitch(BizGatewayConstant.SWITCH_OFF);
            gatewayParam.setOnlineStatus(BizGatewayConstant.ONLINE_STATUS_ON);
            gatewayParam.setStatus(BizGatewayConstant.STATUS_ON);
            // 设置申请授权状态
            gatewayParam.setGrantStatus(GatewayGrantStatusConstant.WAIT_APPLY);
            bizGatewayService.add(gatewayParam);
            log.info(">>> 上报网关成功");
        } else {
            log.info(">>> 上报网关已存在");
        }
        return ResponseData.success();
    }

    /**
     * 获取网关设备对应最新文件
     *
     * @return
     */
    @PostMapping("/getGatewayChannelNewFile")
    public ResponseData getGatewayChannelNewFile(@RequestPart MultipartFile file, @RequestParam(name = "deviceCode") String deviceCode, @RequestParam(name = "micRouter") String micRouter) {
        final BizGatewayParam gatewayParam = new BizGatewayParam();
        gatewayParam.setGatewayCode(deviceCode);
        final BizGateway bizGateway = bizGatewayService.gatewayByGatewayCode(gatewayParam);
        if (ObjectUtil.isNull(bizGateway)) {
            throw new ServiceException(MyConst.GATEWAY_NOT_EXIST);
        }
        final Long fileId = sysFileInfoService.uploadFile(file);
        final BizGatewayNewFileResult gatewayChannelNewFile = bizGatewayNewFileService.getGatewayChannelNewFile(deviceCode, micRouter);

        final BizGatewayNewFile bizGatewayNewFile = new BizGatewayNewFile();
        if(ObjectUtil.isNotNull(gatewayChannelNewFile)){
            bizGatewayNewFile.setId(gatewayChannelNewFile.getId());
            bizGatewayNewFile.setUpdateTime(DateUtil.date());
        }
        bizGatewayNewFile.setGatewayId(bizGateway.getId());
        bizGatewayNewFile.setChannel(micRouter);
        bizGatewayNewFile.setFileId(fileId);
        bizGatewayNewFileService.saveOrUpdate(bizGatewayNewFile);
        return ResponseData.success();
    }

    private void addLog(String error, String gatewayCode, Integer gatewayId, String micRouter, String score, Integer deviceId) {
        final BizExceptionParam bizExceptionParam = new BizExceptionParam();
        bizExceptionParam.setDeviceId(deviceId);
        bizExceptionParam.setErrorName(error);
        bizExceptionParam.setGatewayCode(gatewayCode);
        bizExceptionParam.setAccessToken(null);
        bizExceptionParam.setCreatedAt(DateUtil.now());
        final BizException bizException = bizExceptionService.oneByErrorNameAndToday(bizExceptionParam);
        final BizGatewayChannel channel = bizGatewayChannelService.listByGatewayId(gatewayId, micRouter);
        //第一次故障时间
        String firstTime;
        Integer bizExceptionId;
        if (ObjectUtil.isNotNull(bizException) && error.equals(bizException.getErrorName()) && gatewayCode.equals(bizException.getGatewayCode()) && channel.getDeviceId().equals(bizException.getDeviceId())) {
            // 当天有数据
            firstTime = DateUtil.formatDateTime(bizException.getCreatedAt());
            bizExceptionId = bizException.getId();
        } else {
            // 当天无数据
            firstTime = DateUtil.now();
            final BizExceptionParam bizExceptionInsertParam = new BizExceptionParam();
            if (ObjectUtil.isNotNull(channel)) {
                bizExceptionInsertParam.setDeviceId(channel.getDeviceId());
            }
            bizExceptionInsertParam.setErrorName(error);
            bizExceptionInsertParam.setCreatedAt(firstTime);
            bizExceptionInsertParam.setErrorType(1);
            bizExceptionInsertParam.setGatewayCode(gatewayCode);
            bizExceptionInsertParam.setStatus(0);
            bizExceptionInsertParam.setAccessToken(null);
            bizExceptionId = bizExceptionService.addAndReturnId(bizExceptionInsertParam);
            if (bizExceptionId == 0) {
                throw new ServiceException(MyConst.INSERT_EXCEPTION_ERROR);
            }
        }
        final BizExceptionLogParam bizExceptionLogparam = new BizExceptionLogParam();
        bizExceptionLogparam.setExceptionId(bizExceptionId);
        bizExceptionLogparam.setCreatedAt(firstTime);
        bizExceptionLogparam.setGatewayChannel(micRouter);
        bizExceptionLogparam.setGatewayCode(gatewayCode);
        bizExceptionLogparam.setAccessToken(null);
        bizExceptionLogparam.setVoiceScore(score);
        //设置为1:1时间
        bizExceptionLogparam.setExceptionTime(DateUtil.date());
        bizExceptionLogparam.setCreateTime(DateUtil.date());
        final boolean exceptionLog = exceptionLogService.add(bizExceptionLogparam);
        if (!exceptionLog) {
            throw new ServiceException(MyConst.INSERT_EXCEPTION_LOG_ERROR);
        }
    }

    /**
     * 下载文件
     *
     * @author zxw 2022/11/1
     */
    @GetMapping("/download")
    public void download(@RequestParam(name = "id") Long id, HttpServletResponse response) {
        SysFileInfoParam param = new SysFileInfoParam();
        param.setId(id);
        sysFileInfoService.download(param, response);
    }

    /**
     * 上传文件
     *
     * @author zxw 2022/11/1
     */
    @PostMapping("/upload")
    public ResponseData upload(@RequestPart("file") MultipartFile file) {
        return new SuccessResponseData(sysFileInfoService.uploadFile(file));
    }

    /**
     * 查询当天已下发状态的任务
     *
     * @author rdp
     * @date 2022/10/31 16:17
     * <p>
     * 传参：String gatewayCode 网关编号
     */
    @GetMapping("/getTodayGatewayTask")
    public ResponseData getTodayGatewayTask(@Validated(GatewayTaskParam.getTodayGatewayTask.class) GatewayTaskParam gatewayTaskParam) {
        List<GatewayTask> list = gatewayTaskService.getTodayGatewayTask(gatewayTaskParam);
        if (CollectionUtil.isEmpty(list)) {
            return ResponseData.error(MyConst.NOT_EXISTED_TASK);
        }
        return ResponseData.success(list);
    }

    /**
     * 上报任务执行的回执
     *
     * @author rdp
     * @date 2022/10/31 16:17
     * <p>
     * 传参：String gatewayCode 网关编号、String responseResult 响应结果
     */
    @PostMapping("/callbackGatewayTask")
    public ResponseData callbackGatewayTask(@Validated(GatewayTaskParam.callbackGatewayTask.class) GatewayTaskParam gatewayTaskParam) {
        gatewayTaskService.callbackGatewayTask(gatewayTaskParam);
        return new SuccessResponseData();
    }


    /**
     * 注册模型
     */
    @PostMapping("/registerModel")
    @Transactional(rollbackFor = Exception.class)
    public ResponseData registerModel(@RequestParam("gatewayCode") String gatewayCode, @RequestParam("faultName") String faultName,
                                      @RequestParam("failureLevel") String failureLevel, @RequestParam("expectAccessToken") String expectAccessToken,
                                      @RequestParam("expectGroupId") String expectGroupId, @RequestPart("file") MultipartFile file) {

        Long fileId = sysFileInfoService.uploadFile(file);
        BizGateway gateway = bizGatewayService.getOne(new LambdaQueryWrapper<BizGateway>().eq(BizGateway::getGatewayCode, gatewayCode).last("limit 1"));
        if (ObjectUtil.isEmpty(gateway)) {
            log.warn("设备编号错误,设备编号为：{}", gatewayCode);
            throw new ServiceException(GatewayExceptionEnum.CODE_ERROR);
        }

        log.info(">>>  注册模型，设备编号为：{}", gatewayCode);

        modelService.add(CollectionModel.builder()
                .gatewayId(gateway.getId())
                .faultName(faultName)
                .failureLevel(failureLevel)
                .expectAccessToken(expectAccessToken)
                .expectGroupId(expectGroupId)
                .fileId(fileId)
                .build());
        return new SuccessResponseData();
    }

    /**
     * 更新设备固件
     * @param gatewayCode
     * @return
     */
    @GetMapping("/updateFirmware")
    public ResponseData updateFirmware(@RequestParam("gatewayCode") String gatewayCode) {
        BizGateway gateway = bizGatewayService.getOne(new LambdaQueryWrapper<BizGateway>().eq(BizGateway::getGatewayCode, gatewayCode).last("limit 1"));
        if (ObjectUtil.isEmpty(gateway)) {
            log.warn("设备编号错误,设备编号为：{}", gatewayCode);
            throw new ServiceException(GatewayExceptionEnum.CODE_ERROR);
        }

        log.info(">>>  更新固件，设备编号为：{}", gatewayCode);

        GatewayFirmware gatewayFirmware = gatewayFirmwareService.getOne(new LambdaQueryWrapper<GatewayFirmware>()
                // 查询网关主键
                .like(GatewayFirmware::getGatewayIds, "[" + gateway.getId() + "]")
                // 版本号倒序
                .orderByDesc(GatewayFirmware::getVersionNumber)
                // 只查询一条记录
                .last("limit 1 "));

        return ObjectUtil.isEmpty(gatewayFirmware) ? ResponseData.error("没有发现新的固件信息") : ResponseData.success(gatewayFirmware);
    }

}
